import urllib
from nlu import NLU, UserFrame
from google_prediction import *
from pprint import pprint



#print Train(auth, 'papabot-training/reformat.csv')
model = 'papabot-training/reformat.csv'
n = NLU()
frame = UserFrame()

def getSamples(lines,index):
    samples = []
    for l in lines:
        try:
            phrase = l[index]
            if len(phrase) <=0:
                break
            samples.append(phrase)
        except IndexError:
            break
    return samples


def convertTextForGoogle(text):
    def posConverter(x):
        if x[1] == 'INGR':
            return 'alcohol'
        else:
            return x[0]
    n = NLU()
    ##get pos tags
    textArray = n.pos(text)    
    
    ##extract text and pos
    text = map(posConverter, textArray)
    pos = map(lambda x: x[1], textArray)
    textString = reduce(lambda x,y: x + ' ' + y,text,'').strip()
    posString = reduce(lambda x,y: x + ' ' + y,pos,'').strip()
    
    ##remove any actual drink names, replace with generic term, "alcohol"
    return textString, posString
    

def buildClassification(utterance):
    text,pos = convertTextForGoogle(utterance)
    return {'text':text,'pos':pos}
    

def loadCsv(filename):
    fileString = file(filename).read().replace('\r','').replace('"','')
    rows = fileString.split('\n')
    lines = []
    for r in rows:
        lines.append(r.split(','))
    categories = lines[1]
    sampleDicts = []
    for i in range(len(categories)):
        d = {'classification': categories[i], 'utterances': []}
        d['utterances'] = map(buildClassification, getSamples(lines[2:],i))
        sampleDicts.append(d)
    return sampleDicts
    
def buildCsvForPrediction(sampleDicts, filename):
    csvString = ''
    for samples in sampleDicts:
        for u in samples['utterances']:
            csvString += samples['classification'] + ',' + u['pos'] + ',' + u['text'] + '\n'
    csv = file(filename, 'w')
    csv.write(csvString)
    csv.close()

#sampleDicts = loadCsv('utterances_updated.csv')
#buildCsvForPrediction(sampleDicts,'utterances_classified.csv')

def main():
  """Asks for the user's Google credentials, Prediction API model and queries.
  """

  google_email = 'iencawuil@gmail.com'
  google_password = getpass('Password: ')
  auth = GetAuthentication(google_email, google_password)
  model = 'papabot-training/utterances_classified.csv';
  text = raw_input("sentence to classify: ")
  text,pos = convertTextForGoogle(text)
  query = [text,pos]
  pprint(Predict(auth, model, query))


if __name__ == '__main__':
#   auth = GetAuthentication('iencawuil@gmail.com', '')
#    Train(auth,'papabot-training/utterances_classified.csv')
    main()

